<template>
  <el-dialog
    :close-on-click-modal="false"
    :show-close="false"
    :title="isExport?'导出核销码':'导入核销码'"
    :visible.sync="isImport"
  >
    <div v-if="isExport">
      <el-form
      :rules="rules"
      ref="ruleForm"
      :model="form"
      label-width="120px"
      size="small"
      class="form-box"
      target="_blank"
    >
    <!-- <form ref="ruleForm"  target="_blank">
        <el-radio-group v-model="form.type">
          <el-radio :label="'merchant'">渠道商制码</el-radio>
          <el-radio :label="'shop'">其他平台制码</el-radio>
        </el-radio-group>
        <el-select v-if="form.type=='merchant'" v-model="form.merchant_id" clearable placeholder="请选择渠道商">
          <el-option v-for="item in channelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-input type="text" v-if="form.type=='shop'" v-model="form.shop_name" placeholder="请输入平台名称"></el-input>
        <el-select v-model="form.spec_id" clearable placeholder="请选择规格">
          <el-option v-for="item in allData.spec_list" :key="item.id" :label="item.key_name" :value="item.id"></el-option>
        </el-select>
        <el-input type="number" min="0" v-model.number="form.num"></el-input> -->
      <el-form-item label="制码类型" prop="type">
        <el-radio-group v-model="form.type" @change="codingType">
          <el-radio :label="'merchant'">渠道商制码（有核销通知）</el-radio>
          <el-radio :label="'shop'">其他平台制码（无核销通知）</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="渠道商" v-if="form.type=='merchant'"  prop="merchant_id">
        <el-select v-model="form.merchant_id" clearable placeholder="请选择渠道商">
          <el-option v-for="item in channelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="平台名称" v-if="form.type=='shop'"  prop="shop_name">
        <el-input type="text" v-model="form.shop_name" placeholder="请输入平台名称"></el-input>
      </el-form-item>
      <el-form-item label="规格" v-if="allData.spec_list.length!==0" prop="spec_id">
        <el-select v-model="form.spec_id" clearable placeholder="请选择规格">
          <el-option v-for="item in allData.spec_list" :key="item.id" :label="item.key_name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="制码数量" prop="num">
        <el-input type="number" min="0" v-model.number="form.num"></el-input>
      </el-form-item>
    </el-form>
    </div>
    <form action="" v-else>
      <input type="file" accept=".txt" @change="getFile($event)" />
    </form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="submitFormClose" size="small">关闭</el-button>
      <el-button v-if="isExport" @click="submitFormExp('ruleForm')" type="primary" size="small">导出</el-button>
      <el-button v-else @click="submitFormAdd($event)" type="primary" size="small">导入</el-button>
    </span>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Vue, Prop, Provide } from "vue-property-decorator";
import goodsApi from "@/api/goods";
import channelApi from "@/api/channel";
@Component({
  components: {}
})
export default class freightEditDialog extends Vue {
  // 属性或参数中使用 ！：表示强制解析（告诉typescript编译器，这里一定有值），常用于vue-decorator中的@Prop
  @Prop(Boolean) isImport!: boolean;
  @Prop(Boolean) isExport!: boolean;
  @Prop(Object) allData!: {
    id:number,
    shop_id:number,
    spec_list:any
  };
  @Provide() formMess:any= {
    id:"",
    file:"",
  };
  @Provide() form:any= {
    num:"",
    goods_id:"",
    type: "",
    merchant_id: "",
    shop_name:"",
    spec_id:""
  };
  @Provide() searchMap:{
    type: any,
    appid:any,
  }={
    type: '',
    appid:''
  }
  @Provide() channelList:any=[]
  @Provide() url:any=process.env.VUE_APP_URL+'manage/ticket/ticket/exportTicket?'+this.form

  @Provide() paths:any=process.env.VUE_APP_URL+`manage/ticket/ticket/exportTicket`
  @Provide() rules: any = {
    type: [{ required: true, message: "请选择制码类型", trigger: "change" }],
    merchant_id: [{ required: true, message: "请选择渠道商", trigger: "change" }],
    spec_id: [{ required: true, message: "请选择规格", trigger: "change" }],
    shop_name: [{ required: true, message: "请输入平台名称", trigger: "blur" }],
    num: [{ required: true, message: "请输入数量", trigger: "blur" }],
  };
  @Provide() files: any = '';
  // 拿到上传文件
  getFile(e) {
    this.files= e.target.files[0];
  }
  // 导入
  submitFormAdd(e) {
    this.formMess.id=this.allData.id
    this.formMess.file=this.files
    let formData = new FormData();
    for(var key in this.formMess){
      formData.append(key,this.formMess[key]);
    }
    goodsApi.importCode(formData)
    .then((res: any) => {
      if(res.data.status){
        this.$message({
          message: '操作成功',
          type: "success"
        });
        this.$emit("closeDialog");
        this.$emit("loadData")
      }else{
        this.$message({
          message: res.data.msg,
          type: "error"
        });
      }
    })
  }
  // 导出
  submitFormExp(formName: any) {
    (this.$refs[formName] as any).validate((valid: boolean) => {
      if (valid) {
        this.form.goods_id=this.allData.id;
        goodsApi.exportCode(this.form, 'blob')
          .then((res: any) => {
            if(typeof(res.data) !== 'undefined'){
              goodsApi.exportCode(this.form, 'json').then((res1: any) =>{
                this.$message({
                  message: res1.data.msg,
                  type: "error"
                });
              });
              return false;
            }
          const blob = new Blob([res]);
          this.$message({
            message: '导出成功',
            type: "success"
          });
          this.submitFormClose()
          const filename = '核销码_'+this.allData.shop_id +'.txt'
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = filename
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
            } else {
              navigator.msSaveBlob(blob, filename)
            }
          });
      }
    });
  }
  submitFormClose() {
    this.form= {
      num:"",
      goods_id:"",
      type: "",
      merchant_id: "",
      shop_name:"",
      spec_id:""
    }
    this.$emit('closeDialog')
  }
  created() {
    this.files=''
    channelApi.channelList(1,99999,this.searchMap)
    .then((res: any) => {
        this.channelList = res.data.data.list;
    })
  }
  codingType() {
    (this.$refs['ruleForm']as any).clearValidate();
  }
}
</script>

<style lang="scss" scoped>
.form-box {
  .el-input,
  .el-select {
    width: 200px !important;
  }
}
</style>
